package com.wHitE.servlet;

import com.google.gson.Gson;
import com.wHitE.utils.Result;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

@WebServlet("/userInfo")
public class UserInfoServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("用户信息接口初始化...");
        super.init(config);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("用户信息接口调用...");
        super.service(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取out对象
        PrintWriter out = resp.getWriter();

        // 创建session对象
        HttpSession session = req.getSession();
        // 读取用户session信息
        String username = (String) session.getAttribute("username");

        // 创建application对象
        ServletContext application = this.getServletContext();
        String msg = (String) application.getAttribute("msg");

        // 初始化 object=>json 对象
        Gson gson = new Gson();

        // 处理数据
        ArrayList<String> userInfo = new ArrayList<>();
        userInfo.add(username);
        userInfo.add(msg);

        // 处理并响应给前端
        if (username != null && msg != null) {
            out.print(gson.toJson(Result.success(userInfo)));
        } else {
            out.print(gson.toJson(Result.error("非法进入该地址!请先登录")));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取out对象
        PrintWriter out = resp.getWriter();

        // 创建session对象
        HttpSession session = req.getSession();

        // 创建cookie对象
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("isLogin")) {
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        }

        // 初始化 object=>json 对象
        Gson gson = new Gson();

        // 清除用户session信息并响应给前端
        try {
            session.invalidate();
            out.print(gson.toJson(Result.success()));
        } catch (Exception e) {
            out.print("注销失败!出现错误");
        }

    }

    @Override
    public void destroy() {
        System.out.println("用户信息接口关闭...");
    }
}

